package de.gof.ppstool.xmlexport.ui;

import static de.gof.ppstool.util.LogUtil.begin;
import static de.gof.ppstool.util.LogUtil.end;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import de.gof.ppstool.util.XMLException;
import de.gof.ppstool.util.export.OrderItem;
import de.gof.ppstool.util.export.Output;
import de.gof.ppstool.util.export.ProductionItem;
import de.gof.ppstool.util.export.WorkingTimeItem;

/**
 * XMLExporter
 * Creates a new XML file based on database data
 * ToDos
 * - find the best way to create/format the output file
 * - decide how the output file should be passed on to the user
 * (shown in a text field or as a downloadable file)
 * - remember to change all dots ('.') to commas (',') on all decimal values 
 */
@ManagedBean(name = XMLExporterBean.NAME)
@SessionScoped
public class XMLExporterBean implements Serializable {
	private static final long serialVersionUID = -7925423017513708521L;
	private static final Log LOG = LogFactory.getLog(XMLExporterBean.class);
	private static final boolean DEBUG = LOG.isDebugEnabled();
	private static String outputfile = "";
	public static final String NAME = "xeb";
	private String fileName = "input.xml";
	@ManagedProperty(value = "#{" + XMLExporterBean.NAME + "}")
	private XMLExporterBean xeb;

	public XMLExporterBean() {
		super();
	}

	/**
	 * Creates the XML input file for www.scsim.de
	 * @throws XMLException  
	 * @throws FileNotFoundException  
	 */
	public void createXML(String outputfilelocation) throws XMLException,
			FileNotFoundException {
		if (DEBUG)
			begin(LOG);

		outputfile = outputfilelocation;
		System.out.println("Writing to: " + outputfile);
		Output output = Output.getInstance();
		//Root
		Element root = new Element("Input");
		//Qualitycontrol (fix, never changed!)
		Element qualitycontrol = new Element("qualitycontrol");
		qualitycontrol.setAttribute("type", "no");
		qualitycontrol.setAttribute("losequantity", "0");
		qualitycontrol.setAttribute("delay", "0");
		root.addContent(qualitycontrol);
		//Sellwish											
		Element sellwish = new Element("sellwish");
		Element sellwishItemK = new Element("item");
		//Kind
		sellwishItemK.setAttribute("article", output.getVerkaufsWunschKind()
				.getArticleId().toString());
		sellwishItemK.setAttribute("quantity", output.getVerkaufsWunschKind()
				.getQuantity().toString());
		sellwish.addContent(sellwishItemK);
		Element sellwishItemD = new Element("item");
		//Damen
		sellwishItemD.setAttribute("article", output.getVerkaufsWunschDamen()
				.getArticleId().toString());
		sellwishItemD.setAttribute("quantity", output.getVerkaufsWunschDamen()
				.getQuantity().toString());
		sellwish.addContent(sellwishItemD);
		Element sellwishItemH = new Element("item");
		//Herren
		sellwishItemH.setAttribute("article", output.getVerkaufsWunschHerren()
				.getArticleId().toString());
		sellwishItemH.setAttribute("quantity", output.getVerkaufsWunschHerren()
				.getQuantity().toString());
		sellwish.addContent(sellwishItemH);
		root.addContent(sellwish);
		//SellDirect	
		Element selldirect = new Element("selldirect");
		Element selldirectItemK = new Element("item");
		selldirectItemK.setAttribute("article", output
				.getVerkaufsWunschDirektKind().getArticleId().toString());
		selldirectItemK.setAttribute("quantity", output
				.getVerkaufsWunschDirektKind().getQuantity().toString());
		selldirectItemK.setAttribute("price", output
				.getVerkaufsWunschDirektKind().getPrice().toString());
		selldirectItemK.setAttribute("penalty", output
				.getVerkaufsWunschDirektKind().getPenalty().toString());
		selldirect.addContent(selldirectItemK);
		Element selldirectItemD = new Element("item");
		selldirectItemD.setAttribute("article", output
				.getVerkaufsWunschDirektDamen().getArticleId().toString());
		selldirectItemD.setAttribute("quantity", output
				.getVerkaufsWunschDirektDamen().getQuantity().toString());
		selldirectItemD.setAttribute("price", output
				.getVerkaufsWunschDirektDamen().getPrice().toString());
		selldirectItemD.setAttribute("penalty", output
				.getVerkaufsWunschDirektDamen().getPenalty().toString());
		selldirect.addContent(selldirectItemD);
		Element selldirectItemH = new Element("item");
		selldirectItemH.setAttribute("article", output
				.getVerkaufsWunschDirektHerren().getArticleId().toString());
		selldirectItemH.setAttribute("quantity", output
				.getVerkaufsWunschDirektHerren().getQuantity().toString());
		selldirectItemH.setAttribute("price", output
				.getVerkaufsWunschDirektHerren().getPrice().toString());
		selldirectItemH.setAttribute("penalty", output
				.getVerkaufsWunschDirektHerren().getPenalty().toString());
		selldirect.addContent(selldirectItemH);
		root.addContent(selldirect);
		//orderlist
		Element orderlist = new Element("orderlist");
		List<OrderItem> oil = output.getBestellliste();
		for (int i = 0; i < oil.size(); i++) {
			OrderItem oi = oil.get(i);
			Element orderlistItem = new Element("order");
			orderlistItem.setAttribute("article", oi.getArticleId().toString());
			orderlistItem.setAttribute("quantity", oi.getQuantity().toString());
			orderlistItem.setAttribute("modus", oi.getMode().toString());
			orderlist.addContent(orderlistItem);
		}
		root.addContent(orderlist);
		//productionlist
		Element productionlist = new Element("productionlist");
		List<ProductionItem> pil = output.getProduktionsliste();
		for (int i = 0; i < pil.size(); i++) {
			ProductionItem pi = pil.get(i);
			Element productionlistItem = new Element("production");
			productionlistItem.setAttribute("article", pi.getArticleId()
					.toString());
			productionlistItem.setAttribute("quantity", pi.getQuantity()
					.toString());
			productionlist.addContent(productionlistItem);
		}
		root.addContent(productionlist);
		//workingtimelist
		Element workingtimelist = new Element("workingtimelist");
		List<WorkingTimeItem> wtil = output.getZeitbedarfArbeitsplaetze();
		for (int i = 0; i < wtil.size(); i++) {
			WorkingTimeItem wti = wtil.get(i);
			Element workingtimelistItem = new Element("workingtime");
			workingtimelistItem.setAttribute("station", wti.getStation()
					.toString());
			workingtimelistItem
					.setAttribute("shift", wti.getShift().toString());
			workingtimelistItem.setAttribute("overtime", wti.getOvertime()
					.toString());
			workingtimelist.addContent(workingtimelistItem);
		}
		root.addContent(workingtimelist);
		//add to document
		Document doc = new Document(root);
		//write to file
		writeToFile(doc);
		if (DEBUG)
			end(LOG);

	}

	private void writeToFile(Document doc) throws XMLException,
			FileNotFoundException {
		XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
		FileOutputStream output = new FileOutputStream(outputfile);
		try {
			serializer.output(doc, System.out);
			//TODO remove DEBUG 
			serializer.output(doc, output);
			//Write to file
		} catch (IOException e) {
			e.printStackTrace();
			throw new XMLException("Error writing the XML Output file");
		}

	}

	/**
	 * toString()
	 * @return  String
	 */
	@Override
	public String toString() {
		return "XMLExporter";
	}

	public XMLExporterBean getXeb() {
		return xeb;
	}

	public void setXeb(XMLExporterBean xeb) {
		this.xeb = xeb;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}
